class TareasController < ApplicationController
  # GET /tareas
  # GET /tareas.xml
  def index
  end

  # GET /tareas/1
  # GET /tareas/1.xml
  def show
    @tarea = Tarea.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @tarea }
    end
  end

  # GET /tareas/new
  # GET /tareas/new.xml
  def new
    @tarea = Tarea.new
    @tarea.cargo_id = params[:cargo_id]

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @tarea }
    end
  end

  # GET /tareas/1/edit
  def edit
    @tarea = Tarea.find(params[:id])
  end

  # POST /tareas
  # POST /tareas.xml
  def create
    @tarea = Tarea.new(params[:tarea])

    respond_to do |format|
      if @tarea.save
        flash[:notice] =  'Tarea creada correctamente.'
        format.html { params[:oper].nil? ? redirect_to(@tarea.cargo) : render(:text => "Ok")}
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @tarea.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /tareas/1
  # PUT /tareas/1.xml
  def update
    @tarea = Tarea.find(params[:id])

    respond_to do |format|
      if @tarea.update_attributes(params[:tarea])
        flash[:notice] = 'Tarea actualizado correctamente.'
        format.html { redirect_to(@tarea.cargo) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @tarea.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /tareas/1
  # DELETE /tareas/1.xml
  def destroy
    @tarea = Tarea.find(params[:id])
    @tarea.destroy

    respond_to do |format|
      format.html { redirect_to(tareas_url) }
      format.xml  { head :ok }
    end
  end
  def datos
    registros, count = find_by_params(params, :class => Tarea)
    # Construct a hash from the ActiveRecord result
    return_data = Hash.new()
    return_data[:page] = params[:page]
    return_data[:total] = (count.to_f / params[:rows].to_i).ceil
    return_data[:records] = count

    return_data[:rows] = registros.collect{|u| {:id=>u.id,
        :cell=>[
          u.descripcion,u.peso,u.cargo.try(:nombre)
        ]}}

    # Convert the hash to a json object
    render :text=>return_data.to_json, :layout=>false
  end

end
